/**
 * 获取uuid
 */
export function getUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
    return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
  });
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = "id", pid = "parentId") {
  var res = [];
  var temp = {};
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]["children"]) {
        temp[data[k][pid]]["children"] = [];
      }
      if (!temp[data[k][pid]]["_level"]) {
        temp[data[k][pid]]["_level"] = 1;
      }
      data[k]["_level"] = temp[data[k][pid]]._level + 1;
      temp[data[k][pid]]["children"].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return res;
}

/**
 * date format
 * @param {*} date
 * @param {*} fmt
 */
export function dateFormat(date, fmt = "yyyy-MM-dd hh:mm:ss") {
  //author: meizz
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  return fmt;
}

/**
 * 倒计时（比如验证码）
 * @param {*} seconds
 */
export function countDown(seconds) {
  let sec = seconds;
  return cb => {
    // 先触发一遍
    cb(sec);
    // 再执行递归
    recursiveFoo(sec);

    function recursiveFoo(sec) {
      setTimeout(() => {
        cb(sec);
        sec--;
        if (sec >= 0) {
          recursiveFoo(sec);
        }
      }, 1000);
    }
  };
}

/**
 * 将图片转换为 base64
 * @param {String} url
 * @param {*} callback
 * @param {String} outputFormat
 */
export function convertImgToBase64(url, callback, outputFormat) {
  let canvas = document.createElement("CANVAS");
  let ctx = canvas.getContext("2d");
  let img = new Image();
  img.crossOrigin = "Anonymous";
  img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    let dataURL = canvas.toDataURL(outputFormat || "image/png");
    callback.call(this, dataURL);
    // Clean up
    canvas = null;
  };
  img.src = url;
}

/**
 * 打开新页面
 * @param {String} url 地址
 */
export function open(url) {
  var a = document.createElement("a");
  a.setAttribute("href", url);
  a.setAttribute("target", "_blank");
  a.setAttribute("id", "a-link-temp");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(document.getElementById("a-link-temp"));
}

/**
 * 计算字节大小
 * @param {String} a 原字节数, b 保存小数位
 */
export function formatBytes(a, b = 2) {
  if (0 == a) return "0 Bytes";
  var c = 1024,
    e = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
    f = Math.floor(Math.log(a) / Math.log(c));
  return parseFloat((a / Math.pow(c, f)).toFixed(b)) + " " + e[f];
}
